import json
import requests
from airflow import AirflowException
from airflow.hooks.http_hook import HttpHook


class FeiShuHook(HttpHook):

    def __init__(self,
                 feishu_conn_id='feishu_default',
                 message_type='text',
                 title=None,
                 message=None,
                 at_mobiles=None,
                 at_all=False,
                 level = 'grey',
                 *args,
                 **kwargs
                 ):
        super(FeiShuHook, self).__init__(http_conn_id=feishu_conn_id, *args, **kwargs)
        self.message_type = message_type
        self.message = message
        self.title = title
        self.level = level
        self.at_mobiles = at_mobiles
        self.at_all = at_all

    def _get_endpoint(self):
        """
        Get feishu endpoint for sending message.
        """
        conn = self.get_connection(self.http_conn_id)
        self.base_url = conn.host if conn.host else 'https://bgdmapi.jtexpress.com.cn/monitor/feishu/send'
        token = conn.password
        if not token:
            raise AirflowException('feishu token is requests but get nothing, '
                                   'check you conn_id configuration.')
        return token

    def _build_message(self):
        """
        Build different type of feishu message
        As most commonly used type, text message just need post message content
        rather than a dict like ``{'content': 'message'}``
        """
        if self.message_type  =='text':
            data = {
                'msg_type': self.message_type,
                'content': {
                    'text': self.message
                }
            }
        if self.message_type == 'markdown':
            data = {
                "msg_type": "interactive",
                "card": {
                    "elements": [{
                        "tag": "div",
                        "text": {
                            "content": self.message,
                            "tag": "lark_md"
                        }
                    }],
                    "header": {
                        "title": {
                            "content": self.title,
                            "tag": "plain_text"
                        },
                        "template":self.level
                    }
                }
            }
        return json.dumps(data)

    # def get_conn(self, headers=None):
    #     """
    #     Overwrite HttpHook get_conn because just need base_url and headers and
    #     not don't need generic params
    #
    #     :param headers: additional headers to be passed through as a dictionary
    #     :type headers: dict
    #     """
    #     conn = self.get_connection(self.http_conn_id)
    #     self.base_url = conn.host if conn.host else 'https://bgdmapi.jtexpress.com.cn/monitor/feishu/send'
    #     # self.base_url = "https://open.feishu.cn/"
    #     session = requests.Session()
    #     if headers:
    #         session.headers.update(headers)
    #     return session

    def send(self):
        """
        Send feishu message
        """
        support_type = ['text','markdown']
        if self.message_type not in support_type:
            raise ValueError('feishu Hook only support {} '
                             'so far, but receive {}'.format(support_type, self.message_type))

        data = self._build_message()
        self.log.info('Sending feishu type %s message %s', self.message_type, data)
        token = self._get_endpoint()
        url = self.base_url
        self.log.info('Sending feishu url= %s token= %s', url, token)
        resp = self.run(endpoint='',
                        data=data,
                        headers={'Content-Type': 'application/json','url':token})

        # feishu success send message will with errcode equal to 0
        if int(resp.json().get('code')) != 0:
            raise AirflowException('Send feishu message failed, receive error '
                                   'message %s', resp.text)
        self.log.info('Success Send feishu message')

